﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core.Services.Production;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services.Production;

internal sealed class AlarmRecordService : IAlarmRecordService
{
    private readonly IDBManager _dbManager;

    public AlarmRecordService(IDBManager db) => _dbManager = db;

    public async Task<(List<AlarmRecord> items, int count)> GetPagedAsync(AlarmRecordFilter filter, int pageIndex, int pageItems)
    {
        var sql = new Sql();
        if (!string.IsNullOrEmpty(filter.Classify))
        {
            sql.Where("Classify = @0", filter.Classify);
        }

        if (filter.CreatedTimeStart != null)
        {
            sql.Where("CreatedAt >= @0", filter.CreatedTimeStart);
        }

        if (filter.CreatedTimeEnd != null)
        {
            sql.Where("CreatedAt <= @0", filter.CreatedTimeEnd);
        }

        sql.OrderBy("CreatedAt DESC");

        using var db = _dbManager.Create();
        var data = await db.PageAsync<AlarmRecord>(pageIndex, pageItems, sql);
        return (data.Items, Convert.ToInt32(data.TotalItems));
    }
}
